package com.koron.plan.web.maintainplan.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.koron.bean.base.Response;
import com.koron.bean.query.OrderItem;
import com.koron.bean.query.PageQuery;
import com.koron.bean.standard.jobStock.maintain.vo.MaintainVO;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.bean.workflow.RedirectQuery;
import com.koron.bean.workflow.WorkflowController;
import com.koron.common.core.annocation.CasUser;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.task.web.entity.CronTask;
import com.koron.common.task.web.service.XxlJobService;
import com.koron.plan.config.Constants;
import com.koron.plan.web.common.CommonUtils;
import com.koron.plan.web.maintainplan.bean.entity.MaintainPlanBean;
import com.koron.plan.web.maintainplan.bean.query.MaintainPlanQuery;
import com.koron.plan.web.maintainplan.bean.vo.MaintainPlanDetailVO;
import com.koron.plan.web.maintainplan.service.MaintainPlanService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.ADOConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author twcao
 * @title: MaintainPlanController
 * @projectName GDH_EAM_V2
 * @description: 维保计划Controller
 * @date 2021/8/279:57
 */
@Slf4j
@RestController
@RequestMapping("/maintain")
@Api(tags = "维保计划")
public class MaintainPlanController implements WorkflowController {

    /**
     * 日志
     */
    public static final Logger LOGGER = LoggerFactory.getLogger(MaintainPlanController.class);

    @Autowired
    private MaintainPlanService maintainPlanService;

    @Autowired
    private XxlJobService xxlJobService;

    @Autowired
    private HttpServletRequest request;

    @GetMapping("/selectOne")
    @ApiOperation("根据维保计划id查询详情")
    @ApiImplicitParam(name = "id", value = "维保计划id", required = true, dataType = "String")
    public Response<MaintainPlanDetailVO> selectOne(@CasUser @ApiIgnore EamUser user, @RequestParam String id) {
        String language = request.getHeader("Language");
        return Response.succ(ADOConnection.runTask(user.getCurrDs(), maintainPlanService, "queryById", MaintainPlanDetailVO.class, id, language));
    }

    @PostMapping("/saveOrUpdate")
    @ApiOperation("新增或修改(含删除)维保计划")
    public Response<MaintainPlanDetailVO> saveOrUpdate(@CasUser @ApiIgnore EamUser user, @Validated @RequestBody MaintainPlanDetailVO maintainPlanDetail, BindingResult errorMsg) {
        // 即使断言为真，仍会执行message中的表达式
        Assert.isTrue(!errorMsg.hasErrors(), errorMsg.hasErrors() ? errorMsg.getFieldErrors().get(0).getDefaultMessage() : "");
        CommonUtils.update(maintainPlanDetail, user);
        maintainPlanDetail.setDeptId(StringUtils.isBlank(maintainPlanDetail.getDeptId()) ? user.getOrgId() : maintainPlanDetail.getDeptId());
        maintainPlanDetail.setDeptName(StringUtils.isBlank(maintainPlanDetail.getDeptName()) ? user.getOrgName() : maintainPlanDetail.getDeptName());
        return Response.succ(ADOConnection.runTask(user.getCurrDs(), maintainPlanService, "saveOrUpdate", MaintainPlanDetailVO.class, maintainPlanDetail));
    }

    @GetMapping("/queryList")
    @ApiOperation("维保计划列表查询")
    public Response<PageInfo<MaintainPlanBean>> queryList(@CasUser @ApiIgnore EamUser user, MaintainPlanQuery bean, PageQuery pageInfo) {
        List<OrderItem> orders = pageInfo.getOrders();
        orders.stream().forEach(orderItem -> {
            orderItem.setPrefix("plan");
        });
        if(bean.getCode() == null){
            bean.setCode(Constants.MAINTAIN_PLAN_PREFIX);
        }
        PageHelper.startPage(pageInfo.getPage(), pageInfo.getPageSize(), pageInfo.getOrderBy());
        List<MaintainPlanBean> maintainPlanBeans = ADOConnection.runTask(user.getCurrDs(), maintainPlanService, "queryList", List.class, bean);
        return Response.succ(new PageInfo<>(maintainPlanBeans));
    }

    @GetMapping("/startOrStop")
    @ApiOperation("启用/停止维保计划")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "维保计划id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "startOrStop", value = "启动或停止标志，startOrStop = true，启用维保计划。startOrStop = false，停用维保计划", required = true, dataType = "Boolean")
    })
    public Response<MaintainPlanDetailVO> startOrStop(@CasUser @ApiIgnore EamUser user, @RequestParam String id, @RequestParam boolean startOrStop) {
        return Response.succ(ADOConnection.runTask(user.getCurrDs(), maintainPlanService, "startOrStop", MaintainPlanDetailVO.class, id, startOrStop));
    }

    @GetMapping("/issue")
    @ApiOperation("下发维保计划，生成工单")
    @ApiImplicitParam(name = "id", value = "维保计划id", required = true, dataType = "String")
    public Response<MaintainPlanDetailVO> issue(@CasUser @ApiIgnore EamUser user, @RequestParam String id) {
        return Response.succ(ADOConnection.runTask(user.getCurrDs(), maintainPlanService, "issue", MaintainPlanDetailVO.class, id));
    }


    @DeleteMapping("/deleteById")
    @ApiOperation("根据id删除维保计划")
    @ApiImplicitParam(name = "planId", value = "维保计划id", required = true, dataType = "String")
    public Response<Boolean> deleteById(@CasUser @ApiIgnore EamUser user,@RequestParam String planId) {
        return Response.succ(ADOConnection.runTask(user.getCurrDs(), maintainPlanService, "deleteById", Boolean.class, planId));
    }

    @GetMapping("/queryByPlanId")
    @ApiOperation("根据计划id查找生成的维保计划")
    @ApiImplicitParam(name = "planId", value = "维保计划id", required = true, dataType = "String")
    public Response<PageInfo> queryByPlanId(@CasUser @ApiIgnore EamUser user,@RequestParam String planId, PageQuery pageInfo) {
        PageHelper.startPage(pageInfo.getPage(), pageInfo.getPageSize(), pageInfo.getOrderBy());
        PageInfo<List<MaintainVO>> maintainDTOS = ADOConnection.runTask(user.getCurrDs(), maintainPlanService, "queryByPlanId", PageInfo.class, planId, pageInfo);
        return Response.success(maintainDTOS);
    }

    @GetMapping("/triggerTime")
    @ApiOperation("获取任务将要执行的时间")
    @ApiImplicitParam(name = "num", value = "获取时间的个数，默认5个", dataType = "Integer")
    public Response<List<String>> triggerTime(CronTask cronTask, @RequestParam(defaultValue = "5", required = false) Integer num) {
        return Response.succ(xxlJobService.nextTriggerTime(CommonUtils.parseStrToCron(cronTask), num));
    }

    @Override
    public Response<Object> updateState(@RequestBody RedirectQuery redirectQuery) {
        log.info("workflowUpdate = {}", JSON.toJSONString(redirectQuery));
        ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), maintainPlanService, "workflowUpdate", Boolean.class, redirectQuery);
        return Response.success();
    }

    @Override
    public Response<Object> updateEnd(@RequestBody RedirectQuery redirectQuery) {
        log.info("updateEnd = {}", JSON.toJSONString(redirectQuery));
        MaintainPlanDetailVO maintainPlanDetail = JSON.parseObject(redirectQuery.getFormVariables(), MaintainPlanDetailVO.class);
        // 即使断言为真，仍会执行message中的表达式
        EamUser user = ThreadLocalContext.get();
        CommonUtils.update(maintainPlanDetail, user);
        maintainPlanDetail.setDeptId(StringUtils.isBlank(maintainPlanDetail.getDeptId()) ? user.getOrgId() : maintainPlanDetail.getDeptId());
        maintainPlanDetail.setDeptName(StringUtils.isBlank(maintainPlanDetail.getDeptName()) ? user.getOrgName() : maintainPlanDetail.getDeptName());
        maintainPlanDetail.setStatus(Constants.MAINTAIN_PLAN_STATE.USING);
        ADOConnection.runTask(user.getCurrDs(), maintainPlanService, "saveOrUpdate", MaintainPlanDetailVO.class, maintainPlanDetail);
        return Response.success();
    }

    @Override
    public Response<Object> updateCancel(@RequestBody RedirectQuery redirectQuery) {
        log.info("updateCancel = {}", JSON.toJSONString(redirectQuery));
        return Response.success();
    }
}
